﻿using CloudApiServer.Services;
using log4net.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Forms;
using System.Configuration;
using System.Reflection;
using MySqlX.XDevAPI;

namespace CloudApiServer
{
    public partial class MainFrom : Form
    {
        /// <summary>
        /// Http service.
        /// </summary>
        private HttpService _http;

        public MainFrom()
        {
            InitializeComponent();
            this.Text = $"{Text} {SystemInfo.Version} ({SystemInfo.Versiontime})" ;
            this.StartButton.Enabled = true;
            this.CloseButton.Enabled = false;
            PublicMethod.RefreshConfiguration();
            this.Resize += new EventHandler(MainFrom_Resize);
            
        }
        private void MainFrom_Load(object sender, EventArgs e)
        {

            this.comboBox_DatabaseServer.Text = ApiDatainfo.mysqlUrl;
            this.numericUpDown_DatabasePost.Value = int.Parse(ApiDatainfo.mysqlPost);
            this.PortNum.Value = SystemInfo.localurlpost;

            this.checkBox_OnOffFsiApi.Checked = FsiDatainfo.stateFsiApi;
            this.checkBox_OnOffNeusJiangsuApi.Checked = FsiDatainfo.stateNeusJiangsuApi;
            this.checkBox_OnOffSignno.Checked = FsiDatainfo.statesignon;
            this.checkBox_OnOffFsiEpcApi.Checked = FsiDatainfo.stateFsiEpcApi;
            this.checkBox_OnOffShandongbinzhouApi.Checked = FsiDatainfo.stateShandongBinzhouApi;
            this.checkBox_OnOffShandongDarewayApi.Checked = FsiDatainfo.stateShandongDarewayApi;
            this.checkBox_OnOffShandongJxcApi.Checked = FsiDatainfo.stateShandongJxcApi;
            this.checkBox_OnOffLocalApiInInternal.Checked = FsiDatainfo.stateLocalApiInInternal;
        }



        public void notifyIcon(int time, string title, string info, int type)
        {
            switch (type)
            {
                case 1:
                    notifyIcon_main.ShowBalloonTip(time, title, info, ToolTipIcon.Info);
                    break;
                case 2:
                    notifyIcon_main.ShowBalloonTip(time, title, info, ToolTipIcon.Error);
                    break;
                default:
                    MessageBox.Show("调用未经定义的托盘图标通知类型！请检查代码,当前传入：" + type, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
            }
        }

        /// <summary>
        /// start the http server.
        /// </summary>
        private async void StartButton_Click(object sender, EventArgs e)
        {
            /**
             * start.
             */
            try
            {
                var port = Convert.ToInt32(this.PortNum.Value);
                SystemInfo.localurlpost = Convert.ToInt32(this.PortNum.Value);

                /**
                 * initialize http service.
                 */
                _http = new HttpService(port);

                await _http.StartHttpServer();
                LogHelper.Info("Api服务开启，服务端端口：" + port);
                //MessageBox.Show("API服务已开启", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

                /**
                 * disable the start button and enable the close button.
                 */
                this.StartButton.Enabled = false;
                this.PortNum.Enabled = false;
                this.CloseButton.Enabled = true;
            }
            catch (AggregateException exception)
            {
                /**
                 * PLZ "Run as administrator".
                 */
                if (exception.Flatten().InnerExceptions.Any(ex => ex is AddressAccessDeniedException))
                {
                    string Errnum = LogHelper.GetErrornumber();
                    LogHelper.Error($"[{Errnum}]Api服务访问被拒绝");
                    MessageBox.Show($"[{Errnum}]API服务访问被拒绝，请使用管理员运行控制台应用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception exception)
            {
                string Errnum = LogHelper.GetErrornumber();
                LogHelper.Error($"[{Errnum}]Api服务开启失败！错误内容：{exception.Message}");
                MessageBox.Show($"[{Errnum}]Api服务开启失败！错误内容：{exception.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// close the http server.
        /// </summary>
        private async void CloseButton_Click(object sender, EventArgs e)
        {
            /**
             * close.
             */
            try
            {
                await _http.CloseHttpServer();
                _http.Dispose();
                LogHelper.Info("Api服务已关闭");
                //MessageBox.Show("API服务已关闭", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                /**
                 * disable the start button and enable the close button.
                 */
                this.StartButton.Enabled = true;
                this.PortNum.Enabled = true;
                this.CloseButton.Enabled = false;

            }
            catch (Exception exception)
            {
                string Errnum = LogHelper.GetErrornumber();
                LogHelper.Error($"[{Errnum}]Api服务关闭失败！错误内容：{exception.Message}");
                MessageBox.Show($"[{Errnum}]Api服务关闭失败！错误内容：{exception.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void button_SaveDatabaseInfo_Click(object sender, EventArgs e)
        {
            LogHelper.Info("----------开始保存数据库参数配置----------");
            ApiDatainfo.mysqlUrl = this.comboBox_DatabaseServer.Text;
            PublicMethod.WriteInI("ApiDatainfo", "mysqlUrl", comboBox_DatabaseServer.Text);
            ApiDatainfo.mysqlPost = this.numericUpDown_DatabasePost.Text;
            PublicMethod.WriteInI("ApiDatainfo", "mysqlPost", numericUpDown_DatabasePost.Text);
            LogHelper.Info("----------结束保存数据库参数配置----------");
            MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        private void notifyIcon_main_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void MainFrom_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                // 隐藏窗体而不是最小化到任务栏  
                this.Hide();
                //isHidden = true; // 设置标志，表示窗体已隐藏  
            }
        }

        private void button_SaveFsiInfo_Click(object sender, EventArgs e)
        {

            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    LogHelper.Info("----------开始保存医保控制参数配置----------");
                    FsiDatainfo.stateFsiApi = checkBox_OnOffFsiApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateFsiApi", checkBox_OnOffFsiApi.Checked.ToString());
                    FsiDatainfo.stateNeusJiangsuApi = checkBox_OnOffNeusJiangsuApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateNeusJiangsuApi", checkBox_OnOffNeusJiangsuApi.Checked.ToString());
                    FsiDatainfo.statesignon = checkBox_OnOffSignno.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "statesignon", checkBox_OnOffSignno.Checked.ToString());
                    FsiDatainfo.stateFsiEpcApi=checkBox_OnOffFsiEpcApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateFsiEpcApi", checkBox_OnOffFsiEpcApi.Checked.ToString());
                    FsiDatainfo.stateShandongBinzhouApi=checkBox_OnOffShandongbinzhouApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateShandongBinzhouApi", checkBox_OnOffShandongbinzhouApi.Checked.ToString());
                    FsiDatainfo.stateShandongDarewayApi=checkBox_OnOffShandongDarewayApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateShandongDarewayApi", checkBox_OnOffShandongDarewayApi.Checked.ToString());
                    FsiDatainfo.stateShandongJxcApi= checkBox_OnOffShandongJxcApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateShandongJxcApi", checkBox_OnOffShandongJxcApi.Checked.ToString());
                    FsiDatainfo.stateLocalApiInInternal = checkBox_OnOffLocalApiInInternal.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateLocalApiInInternal", checkBox_OnOffLocalApiInInternal.Checked.ToString());
                    LogHelper.Info("----------结束保存医保控制参数配置----------");

                    scope.Complete();
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存失败！错误内容:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button_ShowFsiSetting_Click(object sender, EventArgs e)
        {
            Frm_FsiSetting f1 = new Frm_FsiSetting();
            f1.ShowDialog();
        }
    }
 }
